package com.guigu.auth.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guigu.auth.entity.AuthResource;
import com.guigu.auth.service.AuthResourceService;
import com.guigu.tms.exception.TmsException;
import com.guigu.tms.result.R;
import com.guigu.tms.result.ResultCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author TaoLong
 * @since 2021-12-06
 */
@RestController
@RequestMapping("/auth/auth-resource")
@Api(tags = "资源管理")
@CacheConfig(cacheNames = "authResource")
public class AuthResourceController {
    @Autowired
    private AuthResourceService resourceService;

    /**
     * 根据菜单Id获取对应的权限数据
     *
     * @param menuId
     * @return
     */
    @ApiOperation("根据菜单Id获取对应的权限数据")
    @ApiImplicitParam(name = "menuId", value = "菜单Id")
    @GetMapping("/queryAllAuthResource/{menuId}")
    public R<List<AuthResource>> queryAllAuthResource(@PathVariable("menuId") String menuId) {
        if (StringUtils.isBlank(menuId)) {
            throw new TmsException(ResultCode.ERROR_CODE, "没有选中对应的菜单");
        }
        QueryWrapper<AuthResource> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("menu_id", menuId);
        return new R<>(ResultCode.SUCCESS_CODE, resourceService.list(queryWrapper));
    }


    /**
     * 添加或修改权限信息
     *
     * @param authResource 资源对象
     * @return
     */
    @ApiOperation("添加或修改权限信息")
    @PostMapping("/addOrUpdateAuthResource")
    @CacheEvict(allEntries = true)
    public R addOrUpdateAuthResource(@RequestBody AuthResource authResource) {
        if (ObjectUtils.isEmpty(authResource)) {
            throw new TmsException(ResultCode.ERROR_CODE, "信息为空!");
        }
        resourceService.saveOrUpdate(authResource);
        return new R(ResultCode.SUCCESS_CODE, "操作成功!");
    }


    /***
     * 根据用户id获取权限列表
     * @param userId
     * @return
     */
    @ApiOperation("根据用户id获取权限列表")
    @GetMapping("/queryResourcesBasedOnUserId/{userId}")
    public R<Set<AuthResource>> queryResourcesBasedOnUserId(@PathVariable("userId") String userId) {
        R<Set<AuthResource>> r = resourceService.queryResourcesBasedOnUserId(userId);
        return r;
    }

    /***
     * 查询全部权限信息
     * @return
     */
    @ApiOperation("查询全部权限信息")
    @GetMapping("/queryAll")
    public R<List<AuthResource>> queryAll() {
        return resourceService.queryAll();
    }
}

